from PIL import Image
import pytesseract
import matplotlib.pyplot as plt

pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
im = Image.open('test_CAPTCHA.jpg')


# print(im.getbands())
img = im.convert('1')
def graying(image):
    w, h = image.size
    gray = Image.new('L', (w, h), 0)
    for i in range(w):
        for j in range(h):
            r, g, b, a = image.getpixel((i, j))
            v = int(r * 0.3 + g * 0.59 + b * 0.11)
            gray.putpixel((i, j), v)
    return gray
# img = graying(im)
# plt.imshow(img)
# plt.show()

def binarization(image):
    w, h = image.size
    tem = 0
    for i in range(w):
        for j in range(h):
            tem += image.getpixel((i, j))
    ave = tem / w / h
    for i in range(w):
        for j in range(h):
            if image.getpixel((i, j)) > ave:
                image.putpixel((i, j), 255)
            else:
                image.putpixel((i, j), 0)
    return image
# imge = binarization(img)
# plt.imshow(imge)
# plt.show()

# img = graying(im)

plt.imshow(img)
plt.show()


def get_pointlist(i, j, r):
    for x in range(i - r, i + r + 1):
        for y in range(j - r, j + r + 1):
            if x == i and y == j:
                continue
            yield (x, y)


def noise_reduction(image, border, r, t):
    w, h = image.size
    # r = 3
    for i in range(r, w - r):
        for j in range(r, h - r):
            if i < w * border or i > w * (1 - border) or j < h * border or j > h * (1 - border):
                image.putpixel((i, j), 255)
            p = image.getpixel((i, j))
            # print(p[3])
            if p < 254:
                count = 0
                for x, y in get_pointlist(i, j, r):
                    if image.getpixel((x, y)) < 254:
                        count += 1

                if count < t * ((r * 2 + 1) ** 2 - 1):
                    image.putpixel((i, j), 255)
    return image


imag = noise_reduction(img, 0.02, 3, 0.3)
imm = noise_reduction(imag, 0.02, 10, 0.3)
plt.imshow(imm)
plt.show()
cha = pytesseract.image_to_string(imm)
print(cha)
